/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cnd;

import java.io.DataInputStream;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.net.*;

/**
 *
 * @author marten
 */
public class CampusSearch {

    private HttpURLConnection connection = null;

    public CampusSearch() {
    }
    public SearchResult[] search(String query){
        return search(query,false,0,0,1);
    }
    public SearchResult[] search(String query, boolean dirsonly){
        return search(query,dirsonly,0,0,1);
    }
    public SearchResult[] search(String query, int page){
        return search(query,false,0,0,page);
    }
    public SearchResult[] search(String query, boolean dirsonly, int minsize,
            int maxsize, int page) {
        //public void search(String query){

        String url = "http://search.student.utwente.nl/api/search/?ajax=results";
        url += "&action=getMoreResults";
        url += "&returnType=xml";
        try{
            url += "&q=" + URLEncoder.encode(query, "UTF-8");
        }catch(Exception e){
            url += "&q=";
        }
        if(minsize>0){
            url += "&minsize=" + minsize;
        }
        if(maxsize>0){
            url += "&maxsize=" + maxsize;
        }
        if (dirsonly) {
            url += "&dirsonly=yes";
        }
        url += "&page=" + page;
        return dosearch(url);
    }

    private SearchResult[] dosearch(String url){
        try {
            URL siteURL = new URL(url);
            DataInputStream theHTML = new DataInputStream(siteURL.openStream());
            DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = fact.newDocumentBuilder();
            Document doc = builder.parse(theHTML);

            Node documentElement = doc.getDocumentElement();
            if (documentElement.getNodeName().equals("campus_search")) {
                NodeList resultlist = documentElement.getChildNodes();
                int x = 0;
                for (int i = 0; i < resultlist.getLength(); i++) {
                    Node thenode = resultlist.item(i);
                    NodeList children = thenode.getChildNodes();
                    if (!(thenode instanceof Text)) {
                        x++;
                    }
                }
                SearchResult[] results = new SearchResult[x];
                int y = 0;
                for (int i = 0; i < resultlist.getLength(); i++) {
                    Node thenode = resultlist.item(i);
                    NodeList children = thenode.getChildNodes();
                    if (!(thenode instanceof Text)) {
                        results[y] = getSearchResult(children);
                        y++;
                    }
                }
                return results;
            } else {
                System.err.println("Response not well formatted");
                return null;
            }
        } catch (Exception e) {
            System.err.println(e);
            return null;
        }
    }

    private SearchResult getSearchResult(NodeList children) {
        SearchResult result = new SearchResult();
        for (int j = 0; j < children.getLength(); j++) {
            Node child = children.item(j);
            String nodename = child.getNodeName();
            String payload = child.getTextContent();
            if (!payload.isEmpty() && !(child instanceof Text)) {
                if (nodename.equals("rank")) {
                    result.setRank(Integer.parseInt(payload));
                } else if (nodename.equals("netbios_name")) {
                    result.setNetbiosName(payload);
                } else if (nodename.equals("ip")) {
                    try {
                        result.setIP(InetAddress.getByName(payload));
                    } catch (Exception e) {
                    }
                } else if (nodename.equals("type")) {
                    if (payload.equals("directory")) {
                        result.setFile(false);
                    } else {
                        result.setFile(true);
                    }
                } else if (nodename.equals("full_path")) {
                    result.setFullPath(payload);
                } else if (nodename.equals("dir")) {
                    result.setDir(payload);
                    //System.out.println(result.dir);
                } else if (nodename.equals("name")) {
                    result.setName(payload);
                } else if (nodename.equals("online")) {
                    if (payload.equals("yes")) {
                        result.setOnline(true);
                    } else {
                        result.setOnline(false);
                    }
                } else if (nodename.equals("size")) {
                    result.setSize(Long.parseLong(payload));
                }
                //System.out.println(nodename + " : " + payload);
            }

        }
        //System.out.println(result.dir);
        return result;
    }
}
